#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"

LTNode* LTBuyNode(LTDataType x) {
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL) {
		perror("malloc");

		exit(1);
	}
	newnode->data = x;
	newnode->next = newnode;
	newnode->prev = newnode;
	return newnode;
}

void LTInit(LTNode** pphead) {
	*pphead = LTBuyNode(-1);
}

void LTPrint(LTNode* phead) {

	LTNode* pcur = phead->next;
	while (pcur != phead) {
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

void LTPushBack(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* newnode = LTBuyNode(x);

	newnode->next = phead;
	newnode->prev = phead->prev;
	
	phead->prev->next = newnode;
	phead->prev = newnode;
}

void LTPushFront(LTNode* phead, LTDataType x) {
	assert(phead);
	LTNode* newnode = LTBuyNode(x);

	newnode->next = phead->next;
	newnode->prev = phead;

	phead->next->prev = newnode;
	phead->next = newnode;
}

void LTPopBack(LTNode* phead) {
	assert(phead&&phead->next!=phead);

	LTNode* del = phead->prev;
	del->prev = phead->prev->prev;
	del->prev->next = phead;
	free(del);
	del = NULL;
}

void LTPopFront(LTNode* phead) {
	assert(phead && phead->next != phead);
	LTNode* del = phead->next;

	phead->next = del->next;
	del->prev = phead;
	free(del);
	del = NULL;

}

LTNode* LTFind(LTNode* phead, LTDataType x) {
	LTNode* pcur = phead->next;
	while (pcur!=phead) {
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x) {
	assert(pos);

	LTNode* newnode = LTBuyNode(x);
	newnode->next = pos->next;
	newnode->prev = pos;
	pos->next->prev = newnode;
	pos->next = newnode;
}

void LTErase(LTNode* pos) {
	assert(pos);

	LTNode* del = pos->next;
	pos->next = del->next;
	del->next->prev = del->prev;
	free(del);
	del = NULL;
}

void LTDestroy(LTNode* phead) {
	LTNode* pcur = phead;

	LTNode* next;
	while (pcur != phead) {
		next = pcur->next;
		free(pcur);
		pcur = pcur->next;
	}
	free(phead);
	phead = NULL;
}